package com.library.servlet.admin;

import com.library.dao.BookDAO;
import com.library.entity.Book;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/admin/editBook")
public class EditBookServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        BookDAO bookDAO = new BookDAO();
        Book book = bookDAO.getBookById(id);
        request.setAttribute("book", book);
        request.getRequestDispatcher("/admin/editBook.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String publisher = request.getParameter("publisher");
        String publishDateStr = request.getParameter("publishDate");
        String location = request.getParameter("location");
        int status = Integer.parseInt(request.getParameter("status"));

        Timestamp publishDate = null;
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(publishDateStr);
            publishDate = new Timestamp(date.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Book book = new Book();
        book.setId(id);
        book.setTitle(title);
        book.setAuthor(author);
        book.setPublisher(publisher);
        book.setPublishDate(publishDate);
        book.setStatus(status);
        book.setLocation(location);

        BookDAO bookDAO = new BookDAO();
        boolean success = bookDAO.updateBook(book);

        if (success) {
            response.sendRedirect(request.getContextPath() + "/admin/books");
        } else {
            request.setAttribute("error", "更新图书失败");
            request.setAttribute("book", book);
            request.getRequestDispatcher("/admin/editBook.jsp").forward(request, response);
        }
    }
}    